package com.film.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.film.domain.Film;
import com.film.service.FilmService;
import com.film.service.impl.FilmServiceImpl;
@WebServlet("/billboard.do")
public class BillboardController extends HttpServlet{
	private FilmService filmservice = new FilmServiceImpl();
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		List<Film> films = filmservice.selectAllFilm();
		List<Film> hasScoreFilm = new ArrayList<>();
		List<Film> noScoreFilm = new ArrayList<>();
		for (Film film : films) {
			if(film.getReviewScore() != null) {
				hasScoreFilm.add(film);
			}else {
				noScoreFilm.add(film);
			}
		}
		for (Film film : noScoreFilm) {
			if(hasScoreFilm.size() < 10) {
				hasScoreFilm.add(film);
			}else {
				break;
			}
		}
		hasScoreFilm.sort(new Comparator<Film>() {
			@Override
			public int compare(Film o1, Film o2) {
				if(null != o1.getReviewScore() && null != o2.getReviewScore()) {
					return o2.getReviewScore().compareTo( o1.getReviewScore());
				}
				return 0;
			}
			
		});
		
		session.setAttribute("filmsReviewScore", hasScoreFilm);
		response.sendRedirect("billboard.jsp");
	}
}
